package yiran.stock.command;

import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import yiran.stock.Stock;
import yiran.stock.StockManager;
import yiran.stock.data.DatabaseManager;
import yiran.stock.lang.LangHelper;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class HoldingsCommand implements StockSubCommand {
    @Override
    public boolean execute(CommandSender sender, String[] args, Stock plugin, StockManager stockManager) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.only-player-holdings"));
            return true;
        }

        Player player = (Player) sender;
        Map<String, Integer> holdings = DatabaseManager.getHoldings(player.getName());
        sender.sendMessage(LangHelper.getString("stocks.holdings-title"));

        if (holdings.isEmpty()) {
            sender.sendMessage(LangHelper.getString("stocks.holdings-empty"));
            return true;
        }

        holdings.forEach((symbol, quantity) -> {
            stockManager.loadStockIfNeeded(symbol);

            String name = stockManager.getStockName(symbol);
            if (name == null) {
                sender.sendMessage(LangHelper.getString("errors.stock-name-error", symbol));
                return;
            }

            Double currentPrice = stockManager.getStockPrice(symbol);
            if (currentPrice == null || currentPrice <= 0) {
                sender.sendMessage(LangHelper.getString("errors.stock-price-error", symbol));
                return;
            }

            double value = currentPrice * quantity;
            double changePercent = stockManager.getChangePercent(symbol);
            sender.sendMessage(LangHelper.getString("stocks.holding-item",
                    name, symbol, quantity, currentPrice, value, changePercent));

            long purchaseTime = DatabaseManager.getPurchaseTime(player.getName(), symbol);
            long currentTime = System.currentTimeMillis();
            long cooldown = 24 * 60 * 60 * 1000;

            if (currentTime - purchaseTime < cooldown) {
                long remainingHours = (cooldown - (currentTime - purchaseTime)) / (60 * 60 * 1000);
                sender.sendMessage(LangHelper.getString("stocks.cooldown-notice", remainingHours));
            }
        });
        return true;
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String[] args, StockManager stockManager) {
        return Collections.emptyList();
    }
}
